package flc.ast.activity;

import androidx.fragment.app.FragmentTransaction;

import android.graphics.Bitmap;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.imgedit.EditType;
import com.stark.imgedit.model.FuncBean;
import com.stark.imgedit.view.CropImageView;
import com.stark.imgedit.view.CustomPaintView;
import com.stark.imgedit.view.StickerView;
import com.stark.imgedit.view.TextStickerView;
import com.stark.imgedit.view.imagezoom.ImageViewTouch;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityPicEditBinding;
import flc.ast.fragment.AddTextFragment;
import flc.ast.BaseEditFragment;
import flc.ast.fragment.ColorTuneFragment;
import flc.ast.fragment.CropFragment;
import flc.ast.fragment.FilterFragment;
import flc.ast.fragment.PaintFragment;
import flc.ast.fragment.StickerFragment;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class PicEditActivity extends BaseAc<ActivityPicEditBinding> {

    public static final int MODE_NONE = 0;
    public static final int MODE_STICKERS = 1;// 贴纸模式
    public static final int MODE_FILTER = 2;// 滤镜模式
    public static final int MODE_CROP = 3;// 剪裁模式
    public static final int MODE_TEXT = 5;// 文字模式
    public static final int MODE_PAINT = 6;//涂鸦模式
    public static final int MODE_COLOR_TUNE = 8;//色调模式

    public static String sImgPath;
    public static int pos;
    private int oldPosition;
    private EditType mEditType = EditType.MAIN;
    private Bitmap mRetBitmap;
    private List<FuncBean> mFuncItems;
    public int mode = MODE_NONE;// 当前操作模式

    public ImageViewTouch mImgView;
    public CropImageView mCropView;
    public CustomPaintView mPaintView;
    public StickerView mStickerView;
    public TextStickerView mTextStickerView;

    private CropFragment mCropFragment;
    private FilterFragment mFilterFragment;
    private StickerFragment mStickerFragment;
    private AddTextFragment mAddTextFragment;
    private PaintFragment mPaintFragment;
    private ColorTuneFragment mColorTuneFragment;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_edit;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPicEditBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvPicEditSave.setOnClickListener(this);
        mDataBinding.ivCancel.setOnClickListener(this);
        mDataBinding.ivApply.setOnClickListener(this);
        mDataBinding.ivPicCut.setOnClickListener(this);
        mDataBinding.ivPicFilter.setOnClickListener(this);
        mDataBinding.ivPicSticker.setOnClickListener(this);
        mDataBinding.ivPicText.setOnClickListener(this);
        mDataBinding.ivPicDoodle.setOnClickListener(this);
        mDataBinding.ivPicAdjust.setOnClickListener(this);

        mImgView = mDataBinding.imageViewTouch;
        mCropView = mDataBinding.cropImgView;
        mStickerView = mDataBinding.stickerView;
        mTextStickerView = mDataBinding.txtStickerView;
        mPaintView = mDataBinding.customPaintView;
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPicCut://裁剪
                oldPosition = pos;
                pos = 0;
                showFragmentByFunc(mFuncItems.get(0));
                break;
            case R.id.ivPicFilter://滤镜
                oldPosition = pos;
                pos = 1;
                showFragmentByFunc(mFuncItems.get(1));
                break;
            case R.id.ivPicSticker://贴纸
                oldPosition = pos;
                pos = 2;
                showFragmentByFunc(mFuncItems.get(2));
                break;
            case R.id.ivPicText://文字
                oldPosition = pos;
                pos = 3;
                showFragmentByFunc(mFuncItems.get(3));
                break;
            case R.id.ivPicDoodle://涂鸦
                oldPosition = pos;
                pos = 4;
                showFragmentByFunc(mFuncItems.get(4));
                break;
            case R.id.ivPicAdjust://色调
                oldPosition = pos;
                pos = 5;
                showFragmentByFunc(mFuncItems.get(5));
                break;
            case R.id.ivCancel://取消
                onBackPressed();
                break;
            case R.id.ivApply://确定
                clickApply();
                break;
            case R.id.tvPicEditSave://保存
                saveImg();
                break;
        }
    }

    @Override
    protected void initData() {
        mRetBitmap = ImageUtils.getBitmap(sImgPath);
        mFuncItems = getFuncData();
        mDataBinding.imageViewTouch.setImageBitmap(mRetBitmap);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);

//        mCropFragment = CropFragment.newInstance();
//        mFilterFragment = FilterFragment.newInstance();
//        mStickerFragment = StickerFragment.newInstance();
//        mAddTextFragment = AddTextFragment.newInstance();
//        mPaintFragment = PaintFragment.newInstance();
//        mColorTuneFragment = ColorTuneFragment.newInstance();

        oldPosition = pos;
        showFragmentByFunc(mFuncItems.get(pos));
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        File file = ImageUtils.save2Album(mRetBitmap, Bitmap.CompressFormat.PNG);
                        //保存到历史记录
                        String filePath = FileUtil.generateFilePath(Content.myRecord, ".png");
                        ImageUtils.save(mRetBitmap, filePath, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_success));
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        }, 500);
                    }
                });
            }
        }, 1000);
    }

    private List<FuncBean> getFuncData() {
        if (mFuncItems != null) {
            return mFuncItems;
        }
        List<FuncBean> funcBeans = new ArrayList<>();
        mFuncItems = funcBeans;
        FuncBean funcBean = null;
        funcBean = new FuncBean(FuncBean.FUNC_CROP, getString(R.string.pic_cut), R.drawable.cj);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_FILTER, getString(R.string.pic_filter), R.drawable.lj);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_EOMJ, getString(R.string.pic_sticker), R.drawable.tz);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_TEXT, getString(R.string.pic_text), R.drawable.wz);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_DRAW, getString(R.string.pic_doodle), R.drawable.ty);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_COLOR_TUNE, getString(R.string.pic_adjust), R.drawable.tj);
        funcBeans.add(funcBean);


        return funcBeans;
    }

    private void showFragmentByFunc(FuncBean funcBean) {
        if (funcBean == null) {
            return;
        }
        if (oldPosition != pos) {
            clearSelection();
        }
        showEdit(funcBean.getName());
        switch (funcBean.getFunc()) {
            case CropFragment.INDEX:
                showCropFragment();
                mDataBinding.ivPicCut.setImageResource(R.drawable.cj);
                break;
            case FilterFragment.INDEX:
                showFilterFragment();
                mDataBinding.ivPicFilter.setImageResource(R.drawable.lj);
                break;
            case StickerFragment.INDEX:
                showStickerFragment();
                mDataBinding.ivPicSticker.setImageResource(R.drawable.tz);
                break;
            case AddTextFragment.INDEX:
                showAddTextFragment();
                mDataBinding.ivPicText.setImageResource(R.drawable.wz);
                break;
            case PaintFragment.INDEX:
                showPaintFragment();
                mDataBinding.ivPicDoodle.setImageResource(R.drawable.ty);
                break;
            case ColorTuneFragment.INDEX:
                showColorTuneFragment();
                mDataBinding.ivPicAdjust.setImageResource(R.drawable.tj);
                break;
            default:
                break;
        }
    }

    /**
     * 点击右下角“勾”后的处理
     */
    private void clickApply() {
        switch (mode) {
            case MODE_CROP:
                mCropFragment.applyCropImage();
                break;
            case MODE_FILTER:
                mFilterFragment.applyFilterImage();
                break;
            case MODE_STICKERS:
                mStickerFragment.applyStickers();
                break;
            case MODE_TEXT:
                mAddTextFragment.applyTextImage();
                break;
            case MODE_PAINT:
                mPaintFragment.applyPaintImage();
                break;
            case MODE_COLOR_TUNE:
                mColorTuneFragment.applyColorTune();
                return;
            default:
                break;
        }
    }


    private void showColorTuneFragment() {
        if (mColorTuneFragment == null) {
            mColorTuneFragment = ColorTuneFragment.newInstance();
        } else {
            mColorTuneFragment.onShow();
        }
        showFragment(mColorTuneFragment);
    }


    private void showPaintFragment() {
        if (mPaintFragment == null) {
            mPaintFragment = PaintFragment.newInstance();
        } else {
            mPaintFragment.onShow();
        }
        showFragment(mPaintFragment);
    }


    private void showAddTextFragment() {
        if (mAddTextFragment == null) {
            mAddTextFragment = AddTextFragment.newInstance();
        } else {
            mAddTextFragment.onShow();
        }
        showFragment(mAddTextFragment);
    }

    private void showStickerFragment() {
        if (mStickerFragment == null) {
            mStickerFragment = StickerFragment.newInstance();
        } else {
            mStickerFragment.onShow();
        }
        showFragment(mStickerFragment);
    }

    private void showFilterFragment() {
        if (mFilterFragment == null) {
            mFilterFragment = FilterFragment.newInstance();
        } else {
            mFilterFragment.onShow();
        }
        showFragment(mFilterFragment);
    }

    private void showCropFragment() {
        if (mCropFragment == null) {
            mCropFragment = CropFragment.newInstance();
        } else {
            mCropFragment.onShow();
        }
        showFragment(mCropFragment);
    }


    private void showFragment(BaseEditFragment baseEditFragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.flFragmentContainer, baseEditFragment);
        fragmentTransaction.commit();
    }

    public Bitmap getMainBit() {
        return mRetBitmap;
    }

    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) {
        if (newBit == null) {
            return;
        }

        if (mRetBitmap != newBit) {
            mRetBitmap = newBit;
            mImgView.setImageBitmap(mRetBitmap);
            mImgView.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    private void showEdit(String name) {
        mDataBinding.tvTitle.setText(name);
    }

    private void clearSelection() {
        mDataBinding.ivPicCut.setImageResource(R.drawable.cj1);
        mDataBinding.ivPicFilter.setImageResource(R.drawable.lj1);
        mDataBinding.ivPicSticker.setImageResource(R.drawable.tz1);
        mDataBinding.ivPicText.setImageResource(R.drawable.wz1);
        mDataBinding.ivPicDoodle.setImageResource(R.drawable.ty1);
        mDataBinding.ivPicAdjust.setImageResource(R.drawable.tj1);
//        if (mCropFragment.isVisible()) {
//            mCropFragment.backToMain();
//        }
//        if (mFilterFragment.isVisible()) {
//            mFilterFragment.backToMain();
//        }
//        if (mStickerFragment.isVisible()) {
//            mStickerFragment.backToMain();
//        }
//        if (mAddTextFragment.isVisible()) {
//            mAddTextFragment.backToMain();
//        }
//        if (mPaintFragment.isVisible()) {
//            mPaintFragment.backToMain();
//        }
//        if (mColorTuneFragment.isVisible()) {
//            mColorTuneFragment.backToMain();
//        }
        if (oldPosition == 0) {
            mCropFragment.backToMain();
        }
        if (oldPosition == 1) {
            mFilterFragment.backToMain();
        }
        if (oldPosition == 2) {
            mStickerFragment.backToMain();
        }
        if (oldPosition == 3) {
            mAddTextFragment.backToMain();
        }
        if (oldPosition == 4) {
            mPaintFragment.backToMain();
        }
        if (oldPosition == 5) {
            mColorTuneFragment.backToMain();
        }
    }

}